class WikiRevision < ActiveRecord::Base

  validates_presence_of     :body
  
  belongs_to :wiki_page
#  belongs_to :editor, :foreign_key => 'user_id', :class_name => "User"
  
  def wikized_body
     self.body.gsub(/\[\[(.*)\]\]/) do |page|
       #begin
       # strip the [[ and ]] elements
       page.gsub!("[[", "")
       page.gsub!("]]", "") 
  
       # check for an image or file otherwise default to wiki link
       if page.index("Image|") 
         # image link in form [[Image|filepath.ext|(caption)|(alignment)]]
         lnk_split = page.split('|')
         
         # FIXME: some small style and wrapping issues with captions
         img = WikiImage.find_by_file(lnk_split[1])
         if lnk_split[2] and lnk_split[2].size>0
         "%(image)!#{img.file.small.url}#{'('+lnk_split[2]+')' if lnk_split[2] and lnk_split[2].size>0}!:/wiki/images/#{img.file.filename} &nbsp;#{lnk_split[2] if lnk_split[2] and lnk_split[2].size>0}%" rescue "%{color:red}The image you are linking to does not exist. Check your sytax or upload your file first.%"
         else
         "!(image). #{img.file.small.url}!"
         end
       elsif page.index("File|")
         # Link directly to file (not the file asset page) in Format [[File|filepath.ext|(link text)]]
         lnk_split = page.split('|')
         
         asset = WikiAsset.find_by_file(lnk_split[1].downcase)
         # NOTE: a bit dangerous because trusting extension
         "\"(fileLink #{asset.file.extension.to_s.downcase}Link)#{lnk_split[2] or asset.file.filename}\":#{asset.file.url}" rescue "%{color:red}The file you are linking to does not exist. Check your sytax or upload your file first.%"
              
       else
         lnk_split = page.split('|')
         if lnk_split.size == 2
           # the first element is the link string, the second is the url
           # also change spaces to underscores
           # NOTE: the paths, will not work if the wiki controler path are changed
           "\"#{WikiPage.exists?(:title => lnk_split[1].gsub('_',' ')) ? '(wiki_link)' : '(no_wiki_link)'}#{lnk_split[0]}\":/wiki/#{lnk_split[1]}"
         else
           "\"#{WikiPage.exists?(:title => page.gsub('_',' ')) ? '(wiki_link)' : '(no_wiki_link)'}#{page.titleize}\":/wiki/#{page}"
         end
       end 
       #rescue
       # "%{color:red}There was an error: Please check your wiki syntax%"  
       #end
    end
  end
  
  # returns if this is the current version of the wiki page
  def current_version?
    self.wiki_page.revisions.index(self) == 0
  end

end
